package e3dds

import (
	"gitee.com/ameise84/e3dds/internal/log"
	"gitee.com/ameise84/e3dds/internal/message"
	"gitee.com/ameise84/e3utils/load_balancer"
)

type service interface {
	RpcService
	load_balancer.Context
	close(bool)
	metaToJson() string
	isLocalService() bool
	isVirtualService() bool
	getBLMode() BLMode
	getSessionID() string
	getState() stateKind
	setSessionID(string)
	setState(stateKind)
	setRpcAddr(string)
	moveActor(func(*actorLocal) bool)
	onPost(*message.Msg)
	onBroadcast(*message.Msg)
	wait()
}

func takeServiceWithJson(js string, localService service) (service, error) {
	var m meta
	if err := m.fromJson(js); err != nil {
		return nil, err
	}

	isLocal := false
	if localService != nil && localService.(*entity).meta.equal(&m) {
		isLocal = true
	}

	if isLocal {
		return localService, nil
	} else {
		return newEntityServiceRemote(m, takeActorRemote(m.ServiceID, m.SessionID, m.RpcAddr)), nil
	}
}

func doMsgPostErr(msg *message.Msg, err error) {
	switch msg.GetKind() {
	case message.MsgEngine:
		log.GetLogger().Warn("post engine msg err").Object(msg).Err(err).Println()
	default:
		log.GetLogger().Error("post msg err").Object(msg).Err(err).Println()
	}
	if msg.IsCall() {
		msg.ResponseError(err)
	}
	message.FreeMessage(msg)
}
